package org.javaforever.oville.operator;

import org.javaforever.oville.NarrowWord;
import org.javaforever.oville.NarrowWords;
import org.javaforever.oville.Word;
import org.javaforever.oville.Words;

public class Code {
	
	public static Word codeWord(NarrowWord source,String varName) {
		byte [] result = new byte[8];
		byte [] src = source.getNarrowWord();
		
		for (int i= 0;i<4;i++) {
			byte bit = src[i];
			byte zero = (byte)0;
			byte b7 = (byte) ((bit&0x80)>0?1:0);
			byte b6 = (byte) ((bit&0x40)>0?1:0);
			
			byte b5 = (byte) ((bit&0x20)>0?1:0);
			byte b4 = (byte) ((bit&0x10)>0?1:0);
			result[2*i] =(byte)(zero |(b7<<6) | (b6<<4)| (b5<<2) | b4);
			
			byte b3 = (byte) ((bit&0x08)>0?1:0);
			byte b2 = (byte) ((bit&0x04)>0?1:0);
			
			byte b1 = (byte)  ((bit&0x02)>0?1:0);
			byte b0 = (byte)  ((bit&0x01)>0?1:0);
			result[2*i+1] =(byte)(zero |(b3<<6) | (b2<<4)|(b1<<2) | b0);
		}
		
		Word w = new Word();
		w.setVarName(varName);
		w.setWord(result);
		return w;
	}
	
	public static Words code(NarrowWords sources,String varName) {
		Words ws = new Words();
		ws.setVarName(varName);
		for (NarrowWord nw:sources.getNarrowWords()) {
			Word w = codeWord(nw,varName);
			ws.addWord(w);
		}
		return ws;
	}
	
	public static void main(String [] argv) throws Exception{
		NarrowWord nw = new NarrowWord();
		byte[] bytes = new byte[4];
		bytes[0] = (byte)0xff;
		bytes[1] = (byte)0xff;
		bytes[2] = (byte)0x55;
		bytes[3] = (byte)0x7f;
		nw.setNarrowWord(bytes);
		Word w = codeWord(nw,"nw");
		System.out.println(w.toQuadStr());
		System.out.println(w.toBinStr());
	}

}
